﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GranitePackageSystem.GranitePackagingService;
using GranitePackageSystem.Models;
using GranitePackageSystem;

namespace GranitePackageSystem.Views.ChildWindows
{
    public partial class OwnershipWindow : ChildWindow
    {
        public GranitePackagingService.Request request;

        public OwnershipWindow(GranitePackagingService.Request req)
        {
            InitializeComponent();
            request = req;
            if (req.QAOwner.Equals(String.Empty))
            {
                boxCurrentOwner.Text = "No Current Owner";
            }
            else
            {
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Looking up Current QA Owner";
                proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted);
                proxy.getUserFriendlyNameAsync(req.QAOwner.Split('\\')[1], req.QAOwner.Split('\\')[0]);
            }
        }

        void proxy_getUserFriendlyNameCompleted(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            boxCurrentOwner.Text = e.Result;
            busyIndicatorMain.IsBusy = false;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void btnTakeOwnership_Click(object sender, RoutedEventArgs e)
        {
            Web.User user = WebContext.Current.User;
            request.QAOwner = user.Name;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Taking Ownership";

            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
            proxy.saveRequestAsync(request);
        }

        void proxy_saveRequestCompleted(object sender, saveRequestCompletedEventArgs e)
        {
            Application.Current.Resources.Remove("Current Request");
            Application.Current.Resources.Add("Current Request", request);
            
            busyIndicatorMain.IsBusy = false;
            this.DialogResult = true;
        }
    }
}

